// pages/gerenZiliao/gerenZiliao.js
import WxValidate from '../../utils/WxValidate.js';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    accuont:'',
    name:"",
    phone:null,
    position: '',
	  sex:['男','女'],//性别列表
	  sexindex:0,//选择的性别下标
    educationindex:0,//选择的 学历的下标
    education: ['博士', '硕士', '本科', '大专', '中专','高中'],//学历数组
	  date:' ',//选择的时间（默认）
	  headimg:'',
    fileId:'',
  },
  //更换头像
	changeImg:function(e){
		var that = this;
		wx.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths
        wx.showToast({
          title: '上传图片',
          icon: 'loading',
          duration: 1500
        })
        wx.uploadFile({
          url: app.globalData.url + '/file/upload', //上传图片接口
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success(res) {
            const data = (JSON.parse(res.data)).data;
            that.setData({
              fileId: data.id,
              headimg: app.globalData.url + '/file/showImage/' + data.id
            })
            wx.showToast({
              title: '上传成功',
              icon: 'loading',
              duration: 1000
            })
          },
          fail(res) {
            console.log(res);
            wx.showToast({
              title: '上传失败',
              icon: 'loading',
              duration: 1000
            })
          }
        })
			}
		})
	},
  //选择性别
	bindsexChange:function(e){
		console.log(e.detail.value)
		var index = e.detail.value;
		this.setData({
			sexindex:index
		})
	},
	// 选择 学历
  bindeducationChange:function(e){
    var educationindex = e.detail.value;
		this.setData({
      educationindex: educationindex
		})
	},
	//选择入党时间
	bindtimeChange:function(e){
		this.setData({
			date:e.detail.value
		})
	},
  //报错 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //验证函数
  initValidate() {
    const rules = {
      name: {
        required: true,
        // minlength: 2
      },
      phone: {
        required: true,
        tel: true
      },
      code: {
        required: true,
      },
      'position': {
        required: true,
      }
    }
    const messages = {
      name: {
        required: '请填写姓名',
        minlength: '请输入正确的名称'
      },
      phone: {
        required: '请填写手机号',
        tel: '请填写正确的手机号'
      },
      code: {
        required: '请填写验证码',
      },
      'position': {
        required: '请输入职务',
      }
    }
    this.WxValidate = new WxValidate(rules, messages);
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);//表单数据
    console.log(this.data.headimg[0]);//头像图片
    var _this = this;
    var params = e.detail.value;
    params['fileId'] = _this.data.fileId;
    params['sex'] = Number(params['sex'])+1;
    params['education'] = Number(params['education']) + 1;
    console.log(params);
    return;
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    } else {
      wx.request({
        header: app.header(),
        url: app.globalData.url + '/workUser/updateUserInfo',//维护修改接口
        data: params,
        method: 'POST',
        success: function (res) {
          if (res.statusCode == 405) {
            app.getLogout();
            return;
          }
          if (!res.data.status == 'error') {
            wx.showToast({
              title: res.data.result,
              icon: 'fail',
              duration: 1500
            })
          } else {
            wx.showToast({
              title: '保存成功',//这里打印出登录成功
              icon: 'success',
              duration: 1000,
              success: function () {
                console.log('haha');
                setTimeout(function () {
                  wx.navigateTo({
                    url: '../setting/setting'
                  })
                }, 2000) //延迟时间
              }
            })
          }
        }
      })
    };

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this =this;
    _this.initValidate();

    wx.request({
      header: app.header(),
      url: app.globalData.url + '/api/getUserInfo',//维护修改接口
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 405) {
          app.getLogout();
          return;
        }
        if(res.data.status=='success'){
         var info = res.data.result;
          _this.setData({
            accuont: info.phone,
            name:info.nickname,
            phone:info.phone,
            position: info.userExtendEO.position,
            sexindex: info.userExtendEO.sex-1,
            educationindex: info.userExtendEO.education-1,
            date: info.userExtendEO.joinPartyDate,
            headimg: app.globalData.url + info.headImage,
            fileId: info.fileId
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})